var disenadorClass = function(){
    me = this;
    /**
     * Variables Principales
     */
    me.nameBol = null;
    me.partBol = null;
    me.typeBol =  null;
    me.script1 = null;
    me.script2 = null;
    /**
     * @objDis: Es objecto tipo Array donde se ingresaran todos los objectos creados los cuales seran mostrados en
     * en en diseñador pero no guardados.
     * @obj: Este objecto tipo Array es donde tambien se ingresaran los objectos creados y verificados los cuales
     * si seran Guardados segun los tipos de Ítems y Orden de los mismos.
     */
    me.objDis = new Array();
    me.obj = new Array();
    me.objId = null;
    /**
     * Variables de los Objectos Principales
     */
    me.flag = false;

    me.grid = null;
    me.tree = null;
    me.itemsPanel = null;
    /**
     * Variables de Objectos dentro de otros Objectos.
     */
    me.layout = null;
    me.toolbarTree = null;
    me.toolbarGrid = null;
    me.toolbarItems = null;
    /**
     * Contadores de Ítem's
     */
    me.contAllItems = 0;
    me.contLabel = 0;
    me.contInput = 0;
    me.contSelect = 0;
    me.contRadio = 0;
    me.contCheck = 0;
    me.contFile = 0;
    me.contCalendar =0;
    /**
     * --------------------------------------------
     */
    /**
     * Se añade un nuevo Tab al Contenedor del Tab's, asi como tambien se le
     * asigna el formato: 3J para la inclusion de demas widget's, asi como se
     * activa como principal.
     */
    me.widgetTab =  function(){
        var disTab;
        mainTab.addTab("disTab", "Diseñador de Boletas", "150px", "-1");
        disTab = mainTab.cells('disTab');
        me.layout = disTab.attachLayout('3J');
        mainTab.setTabActive("disTab");
    },
    /**
     * Metodo que diseña el widget tipo --- Tree, asi como dentro de este se
     * crea el widget tipo ---> ToolBar.
     */
        me.widgetTree = function(){
            var cell;
            /**
             * Se crea las propiedades de la celda
             */
            cell = me.layout.cells('a');
            cell.setText('Listado del Elementos');
            cell.setWidth('200');
            cell.setHeight('300');
            cell.fixSize(true, true);
            /**
             * Se crea un -->"Attach" tipo Tree dentro de la celda.
             */
            me.tree = cell.attachTree();
            /**
             * Se hace un -->"Attach" tipo ToolBar dentro de la Celda
             */
            me.toolbarTree = cell.attachToolbar();
            me.toolbarTree.setIconsPath(mainPath + 'images/icons/');
            me.toolbarTree.addButton("btn_up", 1, "", "icon_23.png", "icon_23d.png");
            me.toolbarTree.setItemToolTip("btn_up", "Mover hacia arriba");
            me.toolbarTree.addButton("btn_down", 2, "", "icon_22.png", "icon_22d.png");
            me.toolbarTree.setItemToolTip("btn_down", "Mover hacia abajo");
            me.toolbarTree.addSeparator("sep1", 3);
            me.toolbarTree.addSpacer("sep1");
            me.toolbarTree.addButton("btn_edit", 4, "", "icon_25.png", "icon_25d.png");
            me.toolbarTree.setItemToolTip("btn_edit", "Editar propiedades del Ítem");
            me.toolbarTree.addButton("btn_delete", 5, "", "icon_17.png", "icon_17d.png");
            me.toolbarTree.setItemToolTip("btn_delete", "Eliminar Ítem");
        },
    /**
     * Metodo que diseña el widget tipo ---> GridProperty, asi como dentro de este otro
     * widget tipo ---> ToolBar.
     */
        me.widgetGrid = function () {
            var cell;
            /**
             * Se crea las propiedades de la celda
             */
            cell = me.layout.cells('c');
            cell.setText('Propiedades del Elemento');
            cell.setWidth('200');
            /**
             * Se hace un ---> "Attach" tipo GridProperty dentro de la celda, asi tambien
             * se le asigna ciertas propiedades.
             */
            me.grid = cell.attachPropertyGrid();
            me.grid.enableValidation(true);
            me.grid.setInitWidths("100,*");
            me.grid.init();
            /**
             * Se hace un --> "Attach" tipo ToolBar dentro de la GridProperty
             */
            me.toolbarGrid = cell.attachToolbar();
            me.toolbarGrid.setIconsPath(mainPath + 'images/icons/');
            me.toolbarGrid.addButton("btn_check", 1, "Verificar", "icon_24.png", "icon_24d.png");
            me.toolbarGrid.setItemToolTip("btn_check", "Verifica si los valores de las propiedades son correctas");
            me.toolbarGrid.addSeparator("sep1", 2);
            me.toolbarGrid.addButton("btn_cancel", 3, "Cancelar", "icon_17.png", "icon_17d.png");
            me.toolbarGrid.setItemToolTip("btn_cancel", "Cancela el Ítem");
        },
    /**
     * Metodo que diseña el widget tipo ---> Cell, asi como dentro de este se crean los
     * widget's Toolbar, StatusBar.
     */
        me.widgetItems = function () {
            //var cell;
            /**
             * Se crea las propiedades de la celda
             */
            me.itemsPanel = me.layout.cells('b');
            me.itemsPanel.setText('Adcionar Elementos');
            /**
             * Se hace un -->"Attach" tipo ToolBar dentro de la Celda
             */
            me.toolbarItems = me.itemsPanel.attachToolbar();
            me.toolbarItems.setIconsPath(mainPath + 'images/icons/');
            me.toolbarItems.loadXML(mainPath + "xml/items.xml", function () {
                me.toolbarItems.addSpacer("sep_1");
            });
            /**
             * Se hace un -->"Attach" tipo StatusBar dentro de la Celda
             */
            me.statusItem = me.itemsPanel.attachStatusBar();
        },
    /**
     * Metodo con todos los Widget's necesarios.
     */
        me.loadGlobalFormBoleta = function(){
            me.widgetTab();
            me.widgetTree();
            me.widgetGrid();
            me.widgetItems();
            me.enabledDisabledToolbars(false);
        },
    /**
     * --------------------------------------------
     */
    /**
     * Metodo que Habilita y Desabilita todos los ToolBar's del Diseñador.
     */
        me.enabledDisabledToolbars = function (status) {
            if (status) {
                me.toolbarItems.forEachItem(function (id) {
                    me.toolbarItems.disableItem(id);
                });
                me.toolbarTree.forEachItem(function (id) {
                    me.toolbarTree.disableItem(id);
                });
                me.toolbarGrid.forEachItem(function (id) {
                    me.toolbarGrid.enableItem(id);
                });
            }
            else {
                me.toolbarItems.forEachItem(function (id) {
                    me.toolbarItems.enableItem(id);
                });
                me.toolbarTree.forEachItem(function (id) {
                    me.toolbarTree.enableItem(id);
                });
                me.toolbarGrid.forEachItem(function (id) {
                    me.toolbarGrid.disableItem(id);
                });
            }
        },
    /**
     * Muestra los Error que se pueden encontrar en el --->GridProperty
     */
        me.getErrorGridProperty = function(){
            var sw;
            me.grid.forEachRow(function (id) {
                sw = me.grid.validateCell(id, 1);
                sw == undefined ? sw = true : null;
            });
            if(sw){
                if (me.grid.cells(1,1).getValue().split(" ")[1] == '') {
                    dhtmlx.alert({
                        text:"Seleccione una MÓDULO para asignar al Ítem creado.",
                        callback: function(){
                            me.grid.selectCell(0, 1, false, false, true);
                        }
                    });
                }
                else if(me.grid.cells(2,1).getValue().split(" ")[1] == ''){
                    dhtmlx.alert({
                        text:"Seleccione un valor para el campo 'PREGUNTA'.",
                        callback: function(){
                            me.grid.selectCell(1, 1, false, false, true);
                        }
                    });
                }
                else if(me.grid.cells(3,1).getValue().split(" ")[1] == ''){
                    dhtmlx.alert({
                        text:"Seleccione un nivel para la 'PREGUNTA'.",
                        callback: function(){
                            me.grid.selectCell(2, 1, false, false, true);
                        }
                    });
                }
                else
                    return true;
            }
            else
                dhtmlx.alert({
                    text:"Los campos de color 'ROJO' son necesarios, ingreselos!!!"
                });
            return false;
        },
    /**
     * Asigna las propiedades por defecto segun el Ítem que se haya ingresado.
     */
        me.getPropertyItems = function (itemName) {
            var //me = this,
                item = new Object();
            switch (itemName) {
                case 'label':
                    me.contLabel++;

                    item.type = "label";
                    item.name = "Texto_" + me.contLabel;
                    item.label = "Texto_" + me.contLabel;
                    item.labelWidth = 300;
                    item.width = 300;
                    break;
                case 'input':
                    me.contInput++;

                    item.type = "input";
                    item.name = "Campo_" + me.contInput;
                    item.label = "Campo_" + me.contInput;
                    item.labelAlign = "right";
                    item.position = "label-left";
                    item.labelWidth = 57;
                    item.inputWidth = 400;
                    item.validate = "";
                    break;
                case 'select':
                    me.contSelect++;

                    item.type = "select";
                    item.name = "Select_"+me.contSelect;
                    item.label = "Select_"+me.contSelect;
                    item.labelWidth = 55;
                    item.labelAlign = "left";
                    item.inputWidth = 140;
                    item.position = "label-left";
                    break;
                case 'radio':
                    me.contRadio++;

                    item.type = "radio";
                    item.name = "Radio_"+me.contRadio;
                    item.label = "Radio_"+me.contRadio;
                    item.labelWidth = 45;
                    item.labelAlign = "left";
                    item.position = "label-left";
                    item.value = "";
                    break;
                case 'checkbox':
                    me.contCheck++;

                    item.type = "checkbox";
                    item.name = "Checkbox_"+me.contCheck;
                    item.label = "Checkbox_"+me.contCheck;
                    item.labelWidth = 67;
                    item.labelAlign = "left";
                    item.position = "label-left";
                    break;
                case 'file':
                    me.contFile++;

                    item.type = "file";
                    item.name = "Archivo_"+me.contFile;
                    item.label = "Subir_Archivo_"+me.contFile;
                    item.labelWidth = 95;
                    item.labelAlign = "left";
                    item.position = "label-left";
                    break;
                case 'calendar':
                    me.contCalendar++;

                    item.type = "calendar";
                    item.name = "Calendario_"+me.contCalendar;
                    item.label = "Calendario_"+me.contCalendar;
                    item.dateFormat = "%d-%m-%Y";
                    item.readonly = true;
                    item.labelWidth = 75;
                    item.labelAlign = "left";
                    item.inputWidth = 75;
                    item.position ="label-left";
                    break;
            }
            item.tooltip = "";
            item.offsetLeft = 15;
            return item;
        },
    /**
     * Metodo donde se asigna los nuevos valores al Ítem ya creado
     *
     * @param idObj -- Es el id del Array --->ObjDis[idObj]
     * @param typeItem -- Tipo de Ítem para asiganar la nueva propiedad
     * @param row -- Numero de fila del GridProperty el cual asignara
     * @param value -- Nuevo valor a asignar
     *
     * @return objDis -- Retorna el objecto ya asignado con las propiedades que le corresponde.
     */
        me.setPropertyItems = function (idObj, typeItem, row, value) {
            var atributs,
                auxObj = new Array();
            switch (typeItem) {
                case 'label':
                    atributs = ["label","className","labelWidth"];
                    break;
                case 'input':
                    atributs = ["label","labelAlign","position","labelWidth","inputWidth","validate","tooltip"];
                    break;
                case 'select':
                    atributs = ["label","labelAlign","position","labelWidth","inputWidth","tooltip"];
                    break;
                case 'radio':
                    atributs = ["name","label","labelAlign","position","labelWidth","value","tooltip"];
                    break;
                case 'checkbox':
                    atributs = ["label","labelAlign","position","labelWidth","tooltip"];
                    break;
                case 'file':
                    atributs = ["label","labelAlign","position","labelWidth","tooltip"];
                    break;
                case 'calendar':
                    atributs = ["label","labelAlign","position","labelWidth","inputWidth","tooltip"];
                    break;
            }
            for(var i=1;i<=4;i++){
                atributs.unshift('');
            }
            //me.objDis[idObj][atributs[row]] = value;
            auxObj[atributs[row]] = value;
            return auxObj;
        },
        me.setDataInGridProperty = function (item) {
            var me = this;
            switch (me.obj[item].type) {
                case 'label':
                    me.grid.cells(1, 1).setValue(me.obj[item].modulo);
                    me.grid.cells(4, 1).setValue(me.obj[item].label);

                    me.obj[item].className == "fontBoldBorder" ? me.grid.cells(5, 1).setValue('fontBold') : me.grid.cells(5, 1).setValue('fontNormal');
                    me.grid.cells(6, 1).setValue(me.obj[item].labelWidth);
                    break;
                case 'input':
                    me.grid.cells(1,1).setValue(me.obj[item].modulo);
                    me.grid.cells(2,1).setValue(me.obj[item].label);
                    me.grid.cells(3,1).setValue(me.obj[item].labelAlign);
                    me.grid.cells(4,1).setValue(me.obj[item].position);
                    me.grid.cells(5,1).setValue(me.obj[item].labelWidth);
                    me.grid.cells(6,1).setValue(me.obj[item].inputWidth);
                    me.grid.cells(7,1).setValue(me.obj[item].validate);
                    if(me.obj[item].tooltip != '')
                        me.grid.cells(8,1).setValue(me.obj[item].tooltip);
                    break;
                case 'select':
                    me.grid.cells(1,1).setValue(me.obj[item].modulo);
                    me.grid.cells(2,1).setValue(me.obj[item].label);
                    me.grid.cells(3,1).setValue(me.obj[item].labelAlign);
                    me.grid.cells(4,1).setValue(me.obj[item].position);
                    me.grid.cells(5,1).setValue(me.obj[item].labelWidth);
                    me.grid.cells(6,1).setValue(me.obj[item].inputWidth);
                    if(me.obj[item].tooltip != '')
                        me.grid.cells(7,1).setValue(me.obj[item].tooltip);
                    break;
                case 'radio':
                    me.grid.cells(1,1).setValue(me.obj[item].modulo);
                    me.grid.cells(2,1).setValue(me.obj[item].name);
                    me.grid.cells(3,1).setValue(me.obj[item].label);
                    me.grid.cells(4,1).setValue(me.obj[item].labelAlign);
                    me.grid.cells(5,1).setValue(me.obj[item].position);
                    me.grid.cells(6,1).setValue(me.obj[item].inputWidth);
                    me.grid.cells(7,1).setValue(me.obj[item].value);
                    if(me.obj[item].tooltip != '')
                        me.grid.cells(8,1).setValue(me.obj[item].tooltip);
                    break;
                case 'checkbox':
                    me.grid.cells(1,1).setValue(me.obj[item].modulo);
                    me.grid.cells(2,1).setValue(me.obj[item].label);
                    me.grid.cells(3,1).setValue(me.obj[item].labelAlign);
                    me.grid.cells(4,1).setValue(me.obj[item].position);
                    me.grid.cells(5,1).setValue(me.obj[item].labelWidth);
                    if(me.obj[item].tooltip != '')
                        me.grid.cells(6,1).setValue(me.obj[item].tooltip);
                    break;
                case 'file':
                    me.grid.cells(1,1).setValue(me.obj[item].modulo);
                    me.grid.cells(2,1).setValue(me.obj[item].label);
                    me.grid.cells(3,1).setValue(me.obj[item].labelAlign);
                    me.grid.cells(4,1).setValue(me.obj[item].position);
                    me.grid.cells(5,1).setValue(me.obj[item].labelWidth);
                    if(me.obj[item].tooltip != '')
                        me.grid.cells(6,1).setValue(me.obj[item].tooltip);
                    break;
                case 'calendar':
                    me.grid.cells(1,1).setValue(me.obj[item].modulo);
                    me.grid.cells(2,1).setValue(me.obj[item].label);
                    me.grid.cells(3,1).setValue(me.obj[item].labelAlign);
                    me.grid.cells(4,1).setValue(me.obj[item].position);
                    me.grid.cells(5,1).setValue(me.obj[item].labelWidth);
                    me.grid.cells(6,1).setValue(me.obj[item].inputWidth);
                    if(me.obj[item].tooltip != '')
                        me.grid.cells(7,1).setValue(me.obj[item].tooltip);
                    break;
            }
        },
    /**
     * Metodo que maneja el Evento --Click-- del widget Panel Item's
     */
        me.onEventClickButtonsItems = function () {
            var itemObj,
                nameItem;
            me.toolbarItems.attachEvent("onClick", function (itemId) {
                nameItem = itemId.split('_');
                if (nameItem[1] != 'end' && nameItem[1] != 'cut') {
                    itemObj = me.getPropertyItems(nameItem[1]);
                    if(itemObj.type){
                        me.grid.loadXML(mainPath + "xml/" + nameItem[1] + ".xml", function () {
                            me.grid.selectCell(3, 1, false, false, true);
                        });
                        me.enabledDisabledToolbars(true);
                        me.objDis.push(itemObj);
                        me.itemsPanel.attachForm(me.objDis);
                    }
                    else
                        dhtmlx.alert({
                            text:"Error el Ítem --> '"+nameItem[1]+"' no tiene ninguna propiedad."
                        });
                }
            });
        },
    /**
     * Metodo que maneja el Evento --EditCell-- del widget GridProperty
     */
        me.onEventEditCellGridProperty = function () {
            var typeObj,
                idObj;
            me.grid.attachEvent("onEditCell", function (stage, numRow, numCol, newValue) {
                if (stage == 2 && newValue != '') {
                    console.log(me.obj[2]['label']);
                    console.log(me.objDis[2]['label']);

                    if(me.objId != null)
                        idObj = me.objId;
                    else
                        idObj = me.objDis.length - 1;//# en esta parte tiene que haber una bandera para determinar si es edicion o no!.
                    //console.log(idObj);

                    //typeObj = me.objDis[idObj].type;
                    //var auxObj = me.setPropertyItems(idObj, typeObj, numRow, newValue);
                    //console.log(auxObj[idObj]);
                    me.obj[2]['label'] = 'xiokull';
                    //me.itemsPanel.attachForm(me.objDis);

                    //console.log(xxx);
                    console.log(me.obj[2]['label']);
                    console.log(me.objDis[2]['label']);
                }
                return true;
            });
        },
    /**
     * Metodo que maneja el Evento --Click-- en los Botones del ToolBar del widget GridProperty
     */
        me.onEventClickButtonsGridProperty = function () {
            var id;
            me.toolbarGrid.attachEvent("onClick", function (itemId) {
                if (itemId == 'btn_check') {
                    if(me.getErrorGridProperty()){
                        id = me.objDis.length - 1;
                        me.obj[me.contAllItems] = me.objDis[id];
                        me.obj[me.contAllItems].modulo = me.grid.cells(1,1).getValue();

                        me.contAllItems++
                        me.enabledDisabledToolbars(false);
                        me.grid.clearAll();

                        var name = me.objDis[id].name.split('_');
                        var text = (me.objDis[id].label.length > 16) ? me.objDis[id].label.substr(0, 14) + '...' : me.objDis[id].label;
                        var item = '<span style="color: #990000;">' + name[0] + '</span>: <span style="color: #666666">' + text + '</span>';

                        me.tree.insertNewItem(0, me.contAllItems, item, 0, 0, 0, 0, 'SELECT');
                    }
                }
                else if(itemId == 'btn_cancel'){
                    console.log(me.obj[me.objId]);
                    console.log(me.objDis[me.objId]);
                    me.grid.clearAll();
                    me.enabledDisabledToolbars(false);
                    //me.objDis.pop();
                    //me.itemsPanel.attachForm(me.objDis);
                }
            })
        },
        me.onEventClickButtonsTree = function () {
            var idx,
                aux,
                idTree;
            me.toolbarTree.attachEvent("onClick", function (itemId) {
                idTree = me.tree.getSelectedItemId();
                if (idTree) {
                    idx = me.tree.getIndexById(idTree);
                    switch(itemId){
                        case 'btn_up':
                            aux = me.obj[idx - 1];
                            if (aux != null)
                                me.obj[idx - 1] = me.obj[idx];
                            break;
                        case 'btn_down':
                            aux = me.obj[idx + 1];
                            if (aux != null)
                                me.obj[idx + 1] = me.obj[idx];
                            break;
                        case 'btn_edit':
                            //me.flag = true;
                            me.objId = idx;
                            //console.log(me.obj[idx].type);
                            //console.log(me.obj[idx]);
                            me.grid.loadXML(mainPath + "xml/" + me.obj[idx].type + ".xml", function () {
                                me.setDataInGridProperty(idx);
                                me.grid.selectCell(3, 1, false, false, true);
                            });
                            me.enabledDisabledToolbars(true);
                            break;
                        case 'btn_delete':
                            me.obj.splice(idx, 1);
                            me.tree.deleteItem(me.tree.getSelectedItemId(), true);
                            break;
                    }
                    if(itemId == 'btn_up' || itemId == 'btn_down'){
                        me.obj[idx] = aux;
                        me.tree.moveItem(idTree, itemId.split('_')[1]);
                        me.tree.selectItem(idTree);
                    }
                    me.itemsPanel.attachForm(me.obj);
                }
                else
                    dhtmlx.alert({
                        text:"Error seleccion un Ítem para poder mover."
                    });
            });
        },
        me.onEventClickItemsTree =function () {
            var id,
                aux;
            me.tree.setOnClickHandler(function (item) {
                id = me.tree.getIndexById(me.tree.getSelectedItemId());
                aux = me.obj[id].className;
                for (var i in me.obj) {
                    if (me.obj[i].className == 'fontBoldBorder')
                        me.obj[i].className = 'fontBold';
                    else if (me.obj[i].className == 'fontNormalBorder')
                        me.obj[i].className = 'fontNormal';
                }
                switch (aux) {
                    case 'fontBold':
                        me.obj[id].className = 'fontBoldBorder';
                        break;
                    case 'fontBoldBorder':
                        me.obj[id].className = "fontBold";
                        break;
                    case 'fontNormal':
                        me.obj[id].className = 'fontNormalBorder';
                        break;
                    case 'fontNormalBorder':
                        me.obj[id].className = 'fontNormal';
                        break;
                    case undefined:
                        me.obj[id].className = 'fontNormalBorder';
                        break;
                }
                me.itemsPanel.attachForm(me.obj);
            });
        },
        me.loadEditFormBoleta = function(){
            me.objDis = me.script1;
            me.obj = me.script2;

            me.itemsPanel.attachForm(me.obj);
            for (var i in me.obj) {
                var name = me.obj[i].name.split('_');
                var text = (me.obj[i].label.length > 16) ? me.obj[i].label.substr(0, 14) + '...' : me.obj[i].label;
                var item = '<span style="color: #990000;">' + name[0] + '</span>: <span style="color: #666666">' + text + '</span>';

                me.tree.insertNewItem(0, 'itemTree_'+i, item, 0, 0, 0, 0, 'SELECT');
            }
        },
        me.widgetMain = function(){
            /**
             * Se verifica de la existencia del Tab.
             */
            if (!searchTab('disTab')) {

                me.nameBol = disenadorwinClass.nameBol;
                me.partBol = disenadorwinClass.partBol;
                me.typeBol = disenadorwinClass.typeBol;

                me.loadGlobalFormBoleta();

                if(me.script1 != null){
                    me.flag = true;
                    me.script1 = JSON.parse(disenadorwinClass.scriptBol1);
                    me.script2 = JSON.parse(disenadorwinClass.scriptBol2);
                    me.loadEditFormBoleta();
                }
            }
            else
                mainTab.setTabActive("disTab");
        }
};
function disenadorAdmin(){
    var DB = new disenadorClass();
    DB.widgetMain();
    DB.onEventClickButtonsItems();
    DB.onEventEditCellGridProperty();
    //DB.onEventClickButtonsGridProperty();
    DB.onEventClickButtonsTree();
    DB.onEventClickItemsTree();

    //prueba.nameBol = 'jorge';
    //prueba.loadGlobalFormBoleta();
}